<template>
  <div style="text-align: left">
    <el-button size="small" type="primary" icon="el-icon-download" @click="dialogVisible = true">表格导出</el-button>
    <el-dialog width="635px" :visible.sync="dialogVisible">
      <el-transfer :titles="['未选', '已选']" v-model="selectedHead" :data="headData"></el-transfer>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOutputFile">确认导出</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import XLSX from "@/assets/sheetmin";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {
    // 原始表头
    headData: Array,
    // 默认选中
    selected: Array,
    // 数据
    tableData: Array,
    // 文件表头
    title: String,
  },
  data() {
    return {
      dialogVisible: false,
      selectedHead: this.selected || [],
    };
  },
  methods: {
    xlsxToFile(heads, res, title) {
      try {
        let cell = [];
        cell.push(heads);
        let cells = cell.concat(res);
        let sheet = XLSX.utils.aoa_to_sheet(cells);
        let book = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(book, sheet, `${title}表`);
        XLSX.writeFile(book, `${title}导出.xlsx`);
      } catch (err) {
        this.$message.error("导出失败！请重试");
      }
      setTimeout(() => {
        this.dialogVisible = false;
      }, 2000);
    },
    getHead(head, headData) {
      let heads = [];
      for (var item of headData) {
        if (head.indexOf(item.key) != -1) {
          heads.push(item.label);
        }
      }
      return heads;
    },
    getTableData(head, tableData) {
      return tableData.map((data) => head.map((i) => data[i]));
    },
    submitOutputFile() {
      let heads = this.getHead(this.selectedHead, this.headData);
      let answers = this.getTableData(this.selectedHead, this.tableData);
      this.xlsxToFile(heads, answers, this.title);
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
};
</script>
<style scoped></style>
